import java.util.ArrayDeque;
import java.util.Deque;
import java.util.LinkedList;

public class IsSymmetric {
    // leetcode 对称二叉树
    // https://leetcode.cn/problems/symmetric-tree/description/?envType=study-plan-v2&envId=top-100-liked
    public boolean isSymmetric(TreeNode root) {
        return isSymmetricChild(root.left, root.right);
    }

    private boolean isSymmetricChild(TreeNode left, TreeNode right) {
        if (left == null && right != null
                || right == null && left != null) {
            return false;
        }
        if (left == null && right == null) return true;
        if (left.val != right.val) return false;
        return isSymmetricChild(left.left,right.right)
                && isSymmetricChild(left.right, right.left);
    }

    /**
     * 非递归实现
     * @param root
     * @return
     */
    public boolean isSymmetric1(TreeNode root) {
        Deque<TreeNode> deque = new LinkedList<>();
        deque.add(root.left);
        deque.add(root.right);
        while (!deque.isEmpty()) {
            TreeNode left = deque.poll();
            TreeNode right = deque.poll();
            if (left == null && right == null) continue;
            if (left == null || right == null || right.val != left.val) return false;
            deque.add(left.left);
            deque.add(right.right);
            deque.add(left.right);
            deque.add(right.left);
        }
        return true;
    }

    public static void main(String[] args) {
        TreeNode A = new TreeNode(1);
        TreeNode B = new TreeNode(2);
        TreeNode C = new TreeNode(2);
        TreeNode D = new TreeNode(3);
        TreeNode E = new TreeNode(3);
        TreeNode F = new TreeNode(4);
        TreeNode G = new TreeNode(4);
        A.left = B;
        A.right = C;
        B.left = D;
        B.right = F;
        C.left = G;
        C.right = E;
        IsSymmetric isSymmetric = new IsSymmetric();
        System.out.println(isSymmetric.isSymmetric1(A));
        Deque<TreeNode> deque = new LinkedList<>();
        deque.add();
    }
}
